import { Base64 } from 'js-base64';
//封装本地存储存储数据与读取数据方法
//存储数据
export const setToken = (token: Token): void => {
  const tokenJsonStr: string = JSON.stringify(token);
  localStorage.setItem('token', tokenJsonStr);
};
//本地存储获取数据
export const getToken = (): Token | null => {
  const tokenJsonStr: string | null = localStorage.getItem('token');
  if (tokenJsonStr === null) {
    return null;
  }
  return JSON.parse(tokenJsonStr) as Token;
};
//本地存储删除数据方法
export const removeToken = (): void => {
  localStorage.removeItem('token');
};

//解析accessToken
export const analysisAccessToken = (accessToken: string): JwtPayload => {
  const jwt: string[] = accessToken.split('.');
  const payload: string = jwt[1];
  const payloadObj: any = Base64.decode(payload);
  return JSON.parse(payloadObj) as JwtPayload;
};

export interface Token {
  accessToken: string;
  tokenType: string;
  refreshToken: string;
  expiresIn: number;
}

export interface JwtPayload {
  sub: string;
  unique_name?: string;
  openId?: string;
  preferred_username?: string;
  given_name?: string;
  role?: string | string[];
  email?: string;
  email_verified?: string;
  phone_number_verified?: string;
  oi_prst?: string;
  oi_au_id?: string;
  client_id?: string;
  oi_tkn_id?: string;
  aud?: string;
  scope?: string;
  jti?: string;
  iss?: string;
  exp?: number;
  iat?: number;
}
